<template>
  <div class="mlnet-main-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>ML.NET 智能预测系统</h1>
      <p class="subtitle">基于机器学习的出库数量动态预测平台</p>
    </div>

    <!-- 功能导航卡片 -->
    <div class="feature-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="feature-card" shadow="hover" @click="navigateTo('prediction')">
            <div class="card-content">
              <div class="icon-wrapper prediction-icon">
                <i class="el-icon-data-analysis"></i>
              </div>
              <h3>出库预测</h3>
              <p>基于历史数据和机器学习算法，预测未来出库数量，提供智能库存管理建议</p>
              <div class="card-footer">
                <el-button type="primary">开始预测</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="feature-card" shadow="hover" @click="navigateTo('preprocessing')">
            <div class="card-content">
              <div class="icon-wrapper preprocessing-icon">
                <i class="el-icon-s-data"></i>
              </div>
              <h3>数据预处理</h3>
              <p>清洗和准备训练数据，进行特征工程，确保数据质量满足机器学习要求</p>
              <div class="card-footer">
                <el-button type="success">数据准备</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="feature-card" shadow="hover" @click="navigateTo('training')">
            <div class="card-content">
              <div class="icon-wrapper training-icon">
                <i class="el-icon-cpu"></i>
              </div>
              <h3>模型训练</h3>
              <p>训练和优化机器学习模型，实时监控训练过程，评估模型性能</p>
              <div class="card-footer">
                <el-button type="warning">开始训练</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 系统状态概览 -->
    <el-card class="system-overview" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>系统状态概览</span>
          <el-button @click="refreshSystemStatus">刷新状态</el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="status-item">
            <div class="status-icon data-status">
              <i class="el-icon-document"></i>
            </div>
            <div class="status-info">
              <div class="status-number">{{ systemStatus.dataRecords }}</div>
              <div class="status-label">数据记录数</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="status-item">
            <div class="status-icon model-status">
              <i class="el-icon-cpu"></i>
            </div>
            <div class="status-info">
              <div class="status-number">{{ systemStatus.activeModels }}</div>
              <div class="status-label">活跃模型数</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="status-item">
            <div class="status-icon accuracy-status">
              <i class="el-icon-trophy"></i>
            </div>
            <div class="status-info">
              <div class="status-number">{{ systemStatus.avgAccuracy }}%</div>
              <div class="status-label">平均准确率</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="status-item">
            <div class="status-icon prediction-status">
              <i class="el-icon-trend-charts"></i>
            </div>
            <div class="status-info">
              <div class="status-number">{{ systemStatus.predictionsToday }}</div>
              <div class="status-label">今日预测数</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 最近活动 -->
    <el-card class="recent-activities" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>最近活动</span>
          <el-button @click="loadRecentActivities">查看更多</el-button>
        </div>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="activity.timestamp"
          :type="getActivityType(activity.type)"
        >
          <div class="activity-content">
            <h4>{{ activity.title }}</h4>
            <p>{{ activity.description }}</p>
            <div class="activity-meta">
              <el-tag :type="getActivityStatusType(activity.status)" size="small">
                {{ activity.status }}
              </el-tag>
              <span class="activity-user">{{ activity.user }}</span>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 快速操作 -->
    <el-card class="quick-actions" shadow="hover">
      <template #header>
        <span>快速操作</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" icon="el-icon-data-analysis" @click="quickPredict">
            快速预测
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="success" icon="el-icon-s-data" @click="quickPreprocess">
            数据检查
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="warning" icon="el-icon-cpu" @click="quickTrain">
            模型重训练
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="info" icon="el-icon-document" @click="generateReport">
            生成报告
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 性能指标 -->
    <el-card class="performance-metrics" shadow="hover">
      <template #header>
        <span>性能指标</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <div class="metric-chart">
            <h4>预测准确率趋势</h4>
            <v-chart class="chart" :option="accuracyTrendOption" :autoresize="true" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="metric-chart">
            <h4>模型响应时间</h4>
            <v-chart class="chart" :option="responseTimeOption" :autoresize="true" />
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import http from '@/http/axiosHelper'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()

// 系统状态
const systemStatus = reactive({
  dataRecords: 0,
  activeModels: 0,
  avgAccuracy: 0,
  predictionsToday: 0
})

// 最近活动
interface Activity {
  id: number
  title: string
  description: string
  timestamp: string
  type: string
  status: string
  user: string
}

const recentActivities = ref<Activity[]>([])

// 准确率趋势图表配置
const accuracyTrendOption = {
  title: {
    text: '预测准确率趋势',
    left: 'center',
    textStyle: {
      fontSize: 14
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value',
    min: 70,
    max: 100
  },
  series: [
    {
      name: '准确率',
      type: 'line',
      data: [85, 87, 89, 91, 88, 92],
      smooth: true,
      lineStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ]
        }
      }
    }
  ]
}

// 响应时间图表配置
const responseTimeOption = {
  title: {
    text: '模型响应时间',
    left: 'center',
    textStyle: {
      fontSize: 14
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value',
    name: '毫秒'
  },
  series: [
    {
      name: '响应时间',
      type: 'line',
      data: [120, 110, 95, 85, 90, 80],
      smooth: true,
      lineStyle: {
        color: '#67C23A'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ]
        }
      }
    }
  ]
}

// 导航到指定页面
const navigateTo = (page: string) => {
  switch (page) {
    case 'prediction':
      router.push('/ML.NET/OutboundPrediction')
      break
    case 'preprocessing':
      router.push('/ML.NET/DataPreprocessing')
      break
    case 'training':
      router.push('/ML.NET/ModelTraining')
      break
    default:
      ElMessage.warning('页面开发中...')
  }
}

// 刷新系统状态
const refreshSystemStatus = async () => {
  try {
    const response = await axios.get('/api/MLNet/GetSystemStatus')
    if (response.data.code === 200) {
      Object.assign(systemStatus, response.data.data)
      ElMessage.success('系统状态已更新')
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
    // 使用模拟数据
    Object.assign(systemStatus, {
      dataRecords: 15420,
      activeModels: 3,
      avgAccuracy: 89.5,
      predictionsToday: 156
    })
  }
}

// 加载最近活动
const loadRecentActivities = async () => {
  try {
    const response = await axios.get('/api/MLNet/GetRecentActivities')
    if (response.data.code === 200) {
      recentActivities.value = response.data.data
    }
  } catch (error) {
    console.error('加载最近活动失败:', error)
    // 使用模拟数据
    recentActivities.value = [
      {
        id: 1,
        title: '模型训练完成',
        description: '随机森林模型训练完成，准确率达到92.3%',
        timestamp: '2024-01-15 14:30:00',
        type: 'training',
        status: 'completed',
        user: '系统管理员'
      },
      {
        id: 2,
        title: '数据预处理完成',
        description: '完成历史出库数据清洗和特征工程',
        timestamp: '2024-01-15 13:45:00',
        type: 'preprocessing',
        status: 'completed',
        user: '数据分析师'
      },
      {
        id: 3,
        title: '批量预测执行',
        description: '为50个产品执行出库量预测',
        timestamp: '2024-01-15 12:20:00',
        type: 'prediction',
        status: 'completed',
        user: '运营专员'
      },
      {
        id: 4,
        title: '模型部署',
        description: '新训练模型已部署到生产环境',
        timestamp: '2024-01-15 11:15:00',
        type: 'deployment',
        status: 'completed',
        user: '系统管理员'
      }
    ]
  }
}

// 快速操作
const quickPredict = () => {
  router.push('/ML.NET/OutboundPrediction')
}

const quickPreprocess = () => {
  router.push('/ML.NET/DataPreprocessing')
}

const quickTrain = () => {
  router.push('/ML.NET/ModelTraining')
}

const generateReport = () => {
  ElMessage.success('报告生成功能开发中...')
}

// 获取活动类型
const getActivityType = (type: string) => {
  switch (type) {
    case 'training': return 'primary'
    case 'preprocessing': return 'success'
    case 'prediction': return 'warning'
    case 'deployment': return 'info'
    default: return 'info'
  }
}

// 获取活动状态类型
const getActivityStatusType = (status: string) => {
  switch (status) {
    case 'completed': return 'success'
    case 'running': return 'warning'
    case 'failed': return 'danger'
    case 'pending': return 'info'
    default: return 'info'
  }
}

onMounted(() => {
  refreshSystemStatus()
  loadRecentActivities()
})
</script>

<style scoped>
.mlnet-main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  color: #303133;
  margin-bottom: 10px;
  font-size: 32px;
  font-weight: bold;
}

.subtitle {
  color: #909399;
  font-size: 16px;
}

.feature-cards {
  margin-bottom: 30px;
}

.feature-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 300px;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.card-content {
  text-align: center;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.icon-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  font-size: 32px;
  color: white;
}

.prediction-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.preprocessing-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.training-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-content h3 {
  color: #303133;
  margin-bottom: 15px;
  font-size: 20px;
}

.card-content p {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 20px;
  flex-grow: 1;
}

.card-footer {
  margin-top: auto;
}

.system-overview,
.recent-activities,
.quick-actions,
.performance-metrics {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 15px;
}

.data-status {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.model-status {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.accuracy-status {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.prediction-status {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.status-info {
  flex-grow: 1;
}

.status-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.status-label {
  color: #909399;
  font-size: 14px;
}

.activity-content h4 {
  color: #303133;
  margin-bottom: 8px;
  font-size: 16px;
}

.activity-content p {
  color: #606266;
  margin-bottom: 10px;
  line-height: 1.5;
}

.activity-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-user {
  color: #909399;
  font-size: 12px;
}

.metric-chart {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.metric-chart h4 {
  margin-bottom: 20px;
  color: #303133;
  text-align: center;
}

.chart {
  height: 250px;
}
</style> 